<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input[type=number] {
        -moz-appearance: textfield;
        }
        input[type=number]::-webkit-outer-spin-button,
        input[type=number]::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }
    </style>
</head>
<body>
    <form action="baidu.com" id="registerForm" method="post">
        <input type="text" name="username" id="">
        <input type="text" name="password" id="">
        <input type="number" name="dasd" value="数字" id="">
        <input type="text" name="phonenumber" id="">
        <button>提交</button>

    </form>

    <script>
        let resgisterForm = document.getElementById('registerForm')
        

        let strategies = {
            isNonEmpty: function(value,errorMsg){
                if(value == ''){
                    return errorMsg
                }
            },
            minLength: function(value,length,errorMsg){
                if(value.length< length){
                    return errorMsg
                }
            },
            isMobile: function(value,errorMsg){
                if(!/^1[3|5|8][0-9]{9}$/.test(value)){
                    return errorMsg
                }
            }
        }

        let validateFun = function(){
            let validator = new Validator()
            validator.add(resgisterForm.username,'isNonEmpty','用户名不能为空')
            validator.add(resgisterForm.password,'minLength:6','密码长度不能小于6位')
            validator.add(resgisterForm.phonenumber,'isMobile','手机号格式不正确')

            let errorMsg = validator.start()
            return errorMsg

        }


        resgisterForm.onsubmit = function(){
            let errorMsg = validateFun()
            if(errorMsg) {
                console.log(errorMsg)
                return false
            }
        }

        let Validator = function(){
            this.cache = []
        }

        Validator.prototype.add = function(dom,rule,errorMsg){
            let array = rule.split(':')
            this.cache.push(function(){
                let strategy = array.shift()
                array.unshift(dom.value)
                array.push(errorMsg)
                return strategies[strategy].apply(dom,array)
            })
        }

        Validator.prototype.start = function(){
            for(let i=0, vaFunc; vaFunc = this.cache[i++];){
                let msg = vaFunc()
                if(msg){
                    return msg
                }
            }
        }

    </script>
</body>
</html>